package com.carrot.newsgallery.controller;

import com.alibaba.druid.sql.ast.SQLKeep;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.carrot.newsgallery.common.R;
import com.carrot.newsgallery.entity.Comment;
import com.carrot.newsgallery.entity.EndorseComment;
import com.carrot.newsgallery.mapper.EndorseCommentMapper;
import com.carrot.newsgallery.service.CommentService;
import com.carrot.newsgallery.utils.HttpUtil;
import com.carrot.newsgallery.utils.ReturnCode;
import com.carrot.newsgallery.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@Slf4j
@Api("论坛评论内容")
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private EndorseCommentMapper endorseCommentMapper;

    @GetMapping("/public")
    @ApiOperation("获取关于一个文章的所有评论")
    public R getComment(@RequestParam int newsFavorId){
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(true,Comment::getArticleId,newsFavorId)
                .eq(true,Comment::getIsBanned,0)
                .orderByAsc(Comment::getCreateTime);
        return R.success(commentService.list(lqw),"查询成功");
    }

    /**
     * 评论某篇文章,该操作任何登陆之后的人都可以做
     * @param request
     * @param comment
     * @return
     */
    @PostMapping
    @ApiOperation("添加一条评论")
    public R addComment(HttpServletRequest request,
                        @RequestBody Comment comment){
        String token = HttpUtil.getToken(request);
        TokenUtil tokenUtil = new TokenUtil();
        int userid = tokenUtil.getUserId(token);

        if (userid != comment.getPosterId())
            return R.fail(ReturnCode.USER_ILLEGAL_OPERATION,"请勿尝试假冒他人评论!");

        if (commentService.save(comment))
            return R.success(null,"添加成功");
        else
            return R.fail(ReturnCode.SERVER_ERROR,"服务器异常,请稍后再试");
    }

    /**
     * 删除一条评论,该操作仅可对属于自己的评论进行操作
     * @param request
     * @param comment
     * @return
     */
    @DeleteMapping
    @ApiOperation("删除一条评论")
    public R deleteComment(HttpServletRequest request,
                           @RequestBody Comment comment){
        String token = HttpUtil.getToken(request);
        TokenUtil tokenUtil = new TokenUtil();
        int userid = tokenUtil.getUserId(token);

        Comment one = commentService.getById(comment.getCommentId());
        //检查操作是否合法
        if (userid != comment.getPosterId())
            return R.fail(ReturnCode.USER_ILLEGAL_OPERATION,"请勿尝试删除他人评论!");
        else if (one == null)
            return R.fail(ReturnCode.DATA_ERROR,"该数据已不存在,请刷新后再试");

        if (commentService.removeById(comment.getCommentId()))
            return R.success(null,"删除成功");
        else
            return R.fail(ReturnCode.SERVER_ERROR,"服务器异常,请稍后再试");

    }

    /**
     * 修改一条评论的内容,该操作仅可对自己的评论进行操作
     * @param request
     * @param comment
     * @return
     */
    @PutMapping
    @ApiOperation("修改一条评论的内容")
    public R modifyComment(HttpServletRequest request,
                           @RequestBody Comment comment){
        String token = HttpUtil.getToken(request);
        TokenUtil tokenUtil = new TokenUtil();
        int userid = tokenUtil.getUserId(token);

        if (userid != comment.getPosterId())
            return R.fail(ReturnCode.USER_ILLEGAL_OPERATION,"请勿尝试修改他人评论!");

        LambdaUpdateWrapper<Comment> luw = new LambdaUpdateWrapper<>();
        luw.eq(true,Comment::getCommentId,comment.getCommentId())
                .set(StringUtils.isNotEmpty(comment.getComment()),Comment::getComment,comment.getComment())
                .set(true,Comment::getCreateTime, LocalDateTime.now());
        if (commentService.update(null,luw))
            return R.success(null,"更新成功");
        else
            return R.fail(ReturnCode.SERVER_ERROR,"服务器异常,请稍后再试");
    }

    /**
     * 登陆后, 任何人对任何公开信息均可执行
     * @param request
     * @param comment
     * @return 返回更新后的或赞数
     */
    @PutMapping("/endorse")
    @ApiOperation("赞一条评论或者取消")
    public R favorComment(HttpServletRequest request, @RequestBody Comment comment){
        String token = HttpUtil.getToken(request);
        TokenUtil tokenUtil = new TokenUtil();
        int userid = tokenUtil.getUserId(token);

        //先判断该评论是否存在
        Comment exist = commentService.getById(comment.getCommentId());
        if (exist == null)
            return R.fail(ReturnCode.DATA_ERROR,"您操作的评论已不存在,请刷新后重试!");
        //存在,再查看是否已经赞过
        LambdaQueryWrapper<EndorseComment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(true,EndorseComment::getCommentId,comment.getCommentId())
                .eq(true,EndorseComment::getPosterId,userid);
        EndorseComment one = endorseCommentMapper.selectOne(lqw);

        int favorNum = exist.getFavorNum();

        //如果不为空,说明该用户已经点赞,现在要取消这个赞
        if (one != null) {
            favorNum -= 1;
            endorseCommentMapper.deleteById(one);
        }
        //为空,说明该用户尚未点赞,现在要点赞
        else {
            favorNum += 1;
            EndorseComment endorseComment = new EndorseComment();
            endorseComment.setCommentId(comment.getCommentId());
            endorseComment.setPosterId(userid);
            endorseCommentMapper.insert(endorseComment);
        }

        LambdaUpdateWrapper<Comment> luw = new LambdaUpdateWrapper<>();
        luw.eq(true,Comment::getCommentId,comment.getCommentId())
                .set(true,Comment::getFavorNum,favorNum);
        if (!commentService.update(null,luw))
            return R.fail(ReturnCode.SERVER_ERROR,"服务器异常,请稍后再试");
        return R.success(favorNum,"更新成功");
    }

}
